package com.z.common.gen.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.z.common.gen.entity.SysDictData;
import com.z.common.gen.service.ISysDictDataService;
import com.z.common.web.base.BaseController;
import com.z.common.web.vo.request.PageVo;
import com.z.common.web.vo.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.List;

/**
 * 数据字典值Controller
 *
 * @author z
 * @date 2022-09-21
 */
@RestController
@RequestMapping("/system/dictData")
public class SysDictDataController extends BaseController {

    private String prefix = "system/dictData";

    @Autowired
    private ISysDictDataService sysDictDataService;

    @GetMapping("/main")
    public ModelAndView main(ModelMap map) {
        map.put("dicts", sysDictDataService.selectDictCode());
        return jumpPage(prefix + "/main");
    }

    /**
     * 查询数据字典值列表
     */
    @ResponseBody
    @GetMapping("/data")
    public Result list(@ModelAttribute SysDictData sysDictData, PageVo pageVo) {
        PageInfo<SysDictData> pageInfo = sysDictDataService.selectSysDictDataPage(sysDictData, pageVo);
        return Result.table(pageInfo);
    }

    /**
     * 新增数据字典值
     */
    @GetMapping("/add")
    public ModelAndView add() {
        return jumpPage(prefix + "/add");
    }

    /**
     * 新增数据字典值
     */
    @ResponseBody
    @PostMapping("/save")
    public Result save(@RequestBody SysDictData sysDictData) {
        return Result.decide(sysDictDataService.save(sysDictData));
    }

    /**
     * 修改数据字典值
     */
    @GetMapping("/edit")
    public ModelAndView edit(String id, ModelMap map) {
        SysDictData sysDictData =sysDictDataService.getById(id);
        map.put("sysDictData", sysDictData);
        return jumpPage(prefix + "/edit");
    }

    /**
     * 修改数据字典值
     */
    @ResponseBody
    @PutMapping("/update")
    public Result update(@RequestBody SysDictData sysDictData) {
        return Result.decide(sysDictDataService.updateById(sysDictData));
    }

    /**
     * 删除数据字典值
     */
    @ResponseBody
    @DeleteMapping("/batchRemove")
    public Result batchRemove(String ids) {
        return Result.decide(sysDictDataService.removeByIds(Arrays.asList(ids.split(","))));
    }

    /**
     * 删除数据字典值
     */
    @ResponseBody
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable("id") String id) {
        return Result.decide(sysDictDataService.removeById(id));
    }

    @GetMapping("selectByCode")
    public Result selectByCode(String typeCode){
        List<SysDictData> list = sysDictDataService.list(
                new QueryWrapper<SysDictData>()
                .eq("type_code", typeCode).eq("is_enable", "1")
        );

        return Result.success(list);
    }
}
